package com.blustreaksw.cyclecoach.userManagment;

import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.UserManagementActivity;
import com.blustreaksw.cyclecoach.UserProfileActivity;
import com.blustreaksw.cyclecoach.data.UserProfile;
import com.blustreaksw.cyclecoach.util.DatePickerFragment;
import com.blustreaksw.cyclecoach.util.ListPickerDialogFragment;

public class Fragment_Wizard_UserProfile extends Fragment {
	
	private static final String TAG = "Fragment_Wizard_UserProfile";
	
	public Button mUnitsButton;
	public Button mGenderButton;
	
	private Button mDatePicker_dateOfBirth;
	private DatePickerFragment mDatePickerFragment;
	private TextView mAgeTextView;
	
	private EditText mUserNameEditText;
	private EditText mUserEmailEditText;
	private EditText mUserWeightEditText;
	private EditText mUserHeightEditText;
	private TextView mUserHeightUnitDescriptor;
	private TextView mUserWeightUnitDescriptor;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		setRetainInstance(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_wizard_edit_user_profile,
				container, false);
		
		UserProfile userProfile = getUserProfileFromActivity();
		getActivity().setTitle("Personal Info");
		
		mUserHeightUnitDescriptor = (TextView)v.findViewById(R.id.userHeight_unitDescriptor);
		mUserWeightUnitDescriptor = (TextView)v.findViewById(R.id.userWeight_unitDescriptor);
		
		mAgeTextView = (TextView)v.findViewById(R.id.age_textView);
		mUserNameEditText = (EditText)v.findViewById(R.id.userName_editText);
		mUserNameEditText.setText(userProfile.getUserName());
		mUserNameEditText.addTextChangedListener(new TextWatcher () {

			@Override
			public void afterTextChanged(Editable s) {
				modifyUserProfile().setUserName(mUserNameEditText.getText().toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) { }
		});
		
		mUserEmailEditText = (EditText)v.findViewById(R.id.userEmail_editText);
		mUserEmailEditText.setText(userProfile.getUserEmail());
		mUserEmailEditText.addTextChangedListener(new TextWatcher () {

			@Override
			public void afterTextChanged(Editable s) {
				modifyUserProfile().setUserEmail(mUserEmailEditText.getText().toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) { }
		});
		
		mUserWeightEditText = (EditText)v.findViewById(R.id.userWeight_editText);
		mUserWeightEditText.setText(Integer.toString(userProfile.getWeight()));
		mUserWeightEditText.addTextChangedListener(new TextWatcher () {

			@Override
			public void afterTextChanged(Editable s) {
				String updatedValue = mUserWeightEditText.getText().toString();
				if(!updatedValue.equals("")){
					modifyUserProfile().setWeight(Integer.parseInt(mUserWeightEditText.getText().toString()));
				}	
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) { }
		});
		mUserWeightEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus) {
					if(Integer.parseInt(mUserWeightEditText.getText().toString()) == 0) {
						mUserWeightEditText.setText("");
					}
				} else {
					if(mUserWeightEditText.getText().toString().equals("")) {
						mUserWeightEditText.setText("0");
					}
				}
				
			}
		});
		
		
		mUserHeightEditText = (EditText)v.findViewById(R.id.userHeight_editText);
		mUserHeightEditText.setText(Integer.toString(userProfile.getHeight()));
		mUserHeightEditText.addTextChangedListener(new TextWatcher () {

			@Override
			public void afterTextChanged(Editable s) {
				String updatedValue = mUserHeightEditText.getText().toString();
				if(!updatedValue.equals("")){
					modifyUserProfile().setHeight(Integer.parseInt(mUserHeightEditText.getText().toString()));
				}	
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) { }
		});
		mUserHeightEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus) {
					if(Integer.parseInt(mUserHeightEditText.getText().toString()) == 0) {
						mUserHeightEditText.setText("");
					}
				} else {
					if(mUserHeightEditText.getText().toString().equals("")) {
						mUserHeightEditText.setText("0");
					}
				}
				
			}
		});
		
		
		
		mUnitsButton = (Button)v.findViewById(R.id.unitsSelector_button);
		
		UserProfile.MeasurementUnits units = userProfile.getDisplayUnits();
		mUnitsButton.setText(units.toString());
		setUnitHints();
			
		mUnitsButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ListPickerDialogFragment listPickerDialog = new ListPickerDialogFragment();
				listPickerDialog.configureListDialog(mUnitsSelectListener, "Measurement Units", R.array.array_units, getActivity());
				listPickerDialog.onCreateDialog(null).show();
			}
		});
		
		mGenderButton = (Button)v.findViewById(R.id.genderSelector_button);
		
		UserProfile.Gender userGender = userProfile.getGender();
		
		if(userGender.equals(UserProfile.Gender.GENDER_MALE)) {
			mGenderButton.setText(getResources().getString(R.string.gender_Male));
		} else if(userGender.equals(UserProfile.Gender.GENDER_FEMALE)) {
			mGenderButton.setText(getResources().getString(R.string.gender_Female));
		} else {
			mGenderButton.setText(getResources().getString(R.string.menu_Select));
		}
		
		mGenderButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ListPickerDialogFragment listPickerDialog = new ListPickerDialogFragment();
				listPickerDialog.configureListDialog(mGenderSelectListener, "Select Gender", R.array.array_gender, getActivity());
				listPickerDialog.onCreateDialog(null).show();
			}
		});
		
		
		/* Point to the Date of Birth selector and configure
		 */
		mDatePickerFragment = new DatePickerFragment();
		mDatePicker_dateOfBirth = (Button)v.findViewById(R.id.dateOfBirth_DatePickerButton);
		mDatePicker_dateOfBirth.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mDatePickerFragment.configureDatePicker(mOnDateSetListener, getUserProfileFromActivity().getDateOfBirth());
				mDatePickerFragment.show(getActivity().getSupportFragmentManager(), null);
			}
			
		});
		
		mDatePickerFragment.updateDateButtonText(mDatePicker_dateOfBirth, getUserProfileFromActivity().getDateOfBirth());
		mAgeTextView.setText(Integer.toString(getUserProfileFromActivity().getAge()));
		
		return v;
	}
	
	OnDateSetListener mOnDateSetListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			modifyUserProfile().setDateOfBirth(year, monthOfYear, dayOfMonth);
			mDatePickerFragment.updateDateButtonText(mDatePicker_dateOfBirth, getUserProfileFromActivity().getDateOfBirth());
			mAgeTextView.setText(Integer.toString(getUserProfileFromActivity().getAge()));
		}
		
	};
	
	DialogInterface.OnClickListener mUnitsSelectListener = new OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			UserProfile.MeasurementUnits units = getUserProfileFromActivity().getDisplayUnits();
			UserProfile.MeasurementUnits newUnits = UserProfile.MeasurementUnits.fromInt(which);
			
			if(!units.equals(newUnits)) {
				modifyUserProfile().setDisplayUnits(newUnits);
				setUnitHints();
				mUnitsButton.setText(newUnits.toString());
				mUserWeightEditText.setText(Integer.toString(getUserProfileFromActivity().getWeight()));
				mUserHeightEditText.setText(Integer.toString(getUserProfileFromActivity().getHeight()));
			}
			
		}
		
	};
	
	DialogInterface.OnClickListener mGenderSelectListener = new OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch(which) {
			case 0:
				mGenderButton.setText(getResources().getString(R.string.gender_Male));
				modifyUserProfile().setGender(UserProfile.Gender.GENDER_MALE);
				break;
			case 1:
				mGenderButton.setText(getResources().getString(R.string.gender_Female));
				modifyUserProfile().setGender(UserProfile.Gender.GENDER_FEMALE);
				break;
			default:
				//mGenderButton.setText(getResources().getString(R.string.menu_Select));
				//getUserProfileFromActivity().setGender(UserProfile.Gender.UNKNOWN);
				break;
			}
			
		}
	};
	

	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		if(((UserProfileActivity)getActivity()).isWizardActivity()) {
			// Show only cancel and next buttons.
			menu.findItem(R.id.action_createUserWizard_cancelButton).setVisible(true);
			menu.findItem(R.id.action_createUserWizard_nextButton).setVisible(true);
			
			// Hidden options
			menu.findItem(R.id.action_createUserWizard_newUser).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_prevButton).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_saveButton).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_restartDeviceScan).setVisible(false);
			menu.findItem(R.id.scanning_indicator)
	        .setActionView(R.layout.progress_indicator).setVisible(false);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {

    		case R.id.action_createUserWizard_cancelButton:
    			// Return to the Select User fragment
    			getActivity().getSupportFragmentManager().popBackStackImmediate();
    			return true;
    			
    		case R.id.action_createUserWizard_nextButton:
    			// Validate the data in the form.
    			/*if(validateFields() == false) {
    				return true;
    			}*/
    			
    			Fragment fragment;
    			if((fragment = getActivity().getSupportFragmentManager().
    					findFragmentByTag(UserManagementActivity.FRAGMENT_SENSOR_CONFIGURATION)) == null) {
    				fragment = new Fragment_Wizard_SensorConfiguration();
    			}
    			
    			// Transition to the next fragment.
    			getActivity().getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragmentContainer,  fragment, UserManagementActivity.FRAGMENT_SENSOR_CONFIGURATION)
					.addToBackStack(null)
					.commit();
    			return true;
    		
    		// Hidden from the user.
    		case R.id.action_createUserWizard_newUser:
    		case R.id.action_createUserWizard_restartDeviceScan:
    		case R.id.action_createUserWizard_prevButton:
    		case R.id.action_createUserWizard_saveButton:
    			return true;
    		
    		default:
    			return super.onOptionsItemSelected(item); 
    	}
    }
	
	private UserProfile getUserProfileFromActivity() { return ((UserProfileActivity)getActivity()).getUserProfile(); }
	
	private UserProfile modifyUserProfile() { 
		((UserProfileActivity)getActivity()).setProfileModified(); 
		return ((UserProfileActivity)getActivity()).getUserProfile(); 
	}
	
	private boolean validateFields() { return ((UserProfileActivity)getActivity()).validateFields(); }
	
	private void setUnitHints() {
		UserProfile.MeasurementUnits units = getUserProfileFromActivity().getDisplayUnits();
		if(units.equals(UserProfile.MeasurementUnits.ENGLISH)) {
			mUserHeightUnitDescriptor.setText("in");
			mUserWeightUnitDescriptor.setText("lbs");
		} else {
			mUserHeightUnitDescriptor.setText("cm");
			mUserWeightUnitDescriptor.setText("kg");
		}
	}
	
	
}